package com.tianji.aigc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tianji.aigc.config.SessionProperties;
import com.tianji.aigc.entity.ChatSession;
import com.tianji.aigc.mapper.ChatSessionMapper;
import com.tianji.aigc.memory.RedisChatMemory;
import com.tianji.aigc.service.IChatSessionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.aigc.vo.ChatHistoryVO;
import com.tianji.aigc.vo.MessageVO;
import com.tianji.aigc.vo.SessionVO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.UserContext;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * <p>
 * 对话session 服务实现类
 * </p>
 *
 * @author lty
 * @since 2025-09-02
 */
@Service
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements IChatSessionService {

    @Autowired
    private SessionProperties sessionProperties;

    /**
     * 创建会话
     * @param num
     * @return
     */

    @Override
    public SessionVO addChat( Integer num) {
        //生成会话Id
        String sessionId = IdUtil.fastSimpleUUID();

        //保存会话历史
        ChatSession chatSession = ChatSession.builder()
                .sessionId(sessionId)
                .userId(UserContext.getUser())
                .build();
        this.save(chatSession);

        //随机选择三个问题
        List<SessionVO.Example> examples = sessionProperties.getExamples();
        Collections.shuffle( examples);

        List<SessionVO.Example> exampleList = examples.stream().limit(num).toList();

        return SessionVO.builder()
                .sessionId(sessionId)
                .title(sessionProperties.getTitle())
                .describe(sessionProperties.getDescribe())
                .examples(exampleList)
                .build();
    }

    /**
     * 随机展示三个问题
     * @param num
     * @return
     */


    @Override
    public List<SessionVO.Example> getHotSession(Integer num) {
        List<SessionVO.Example> examples = sessionProperties.getExamples();
        Collections.shuffle( examples);
        List<SessionVO.Example> exampleList = examples.stream().limit(num).toList();
        return  exampleList;
    }


    @Autowired
    private RedisChatMemory redisChatMemory;
    @Override
    public List<MessageVO> getList(String sessionId) {
        ChatSession chatSession = this.getOne(Wrappers.<ChatSession>lambdaQuery().eq(ChatSession::getSessionId, sessionId));
        if(ObjectUtil.isEmpty(chatSession)){
            throw new BizIllegalException("会话不存在");
        }

        List<Message> messages = redisChatMemory.get(UserContext.getUser() + ":" + sessionId, 1000);
        return messages.stream().filter(message -> message.getMessageType().equals(MessageType.USER)||message.getMessageType().equals(MessageType.ASSISTANT))
                .map(message -> MessageVO.builder().type(message.getMessageType()).content(message.getText()).build()).toList();
    }

    @Async
    @Override
    public void updateSessionTitle(String question, String sessionId, Long userId) {
        //判断会话是否存在
        ChatSession chatSession = this.lambdaQuery()
                .eq(ChatSession::getSessionId, sessionId)
                .eq(ChatSession::getUserId, userId)
                .one();

        if (chatSession==null){
            throw  new BadRequestException("会话记录不存在无法更新");
        }
        //更新用户会话记录里的标题（第一次对话的问题）
        this.lambdaUpdate()
                .eq(ChatSession::getUserId,userId)
                .eq(ChatSession::getSessionId,sessionId)
                .set(StrUtil.isNotEmpty(chatSession.getTitle()),ChatSession::getUpdateTime, LocalDateTime.now())
                .set(StrUtil.isEmpty(chatSession.getTitle()),ChatSession::getTitle, question)
                .update();
    }

    @Override
    public Map<String, List<ChatHistoryVO>> getHistoryList() {
        //查询最近30条会话记录
        List<ChatSession> chatSessionList = this.lambdaQuery().eq(ChatSession::getUserId, UserContext.getUser())
                .orderByDesc(ChatSession::getUpdateTime)
                .last("limit 30")
                .list();
        if (CollUtil.isEmpty(chatSessionList)) {
            return Map.of();
        }

        //类型转换
        List<ChatHistoryVO> chatHistoryVOList = BeanUtil.copyToList(chatSessionList, ChatHistoryVO.class);

        Map<String, List<ChatHistoryVO>> chatHistoryVoListMap = CollStreamUtil.groupByKey(chatHistoryVOList, vo -> {
            long between = Math.abs(ChronoUnit.DAYS.between(vo.getUpdateTime().toLocalDate(), LocalDate.now()));
            if(between<=0) {
                return "当天";
            } else if(between<=30){
                return "最近30天";
            } else if(between<=365) {
                return "最近1年";
            } else {
                return "1年以上";
            }
        });
        return chatHistoryVoListMap;
    }
}
